// 智能加载状态管理工具
const app = getApp()

class SmartLoadingManager {
  constructor() {
    this.pageLoadingStates = new Map()
    this.requestLoadingStates = new Map()
    this.defaultLoadingTime = 800
    this.minLoadingTime = 300
  }

  // 页面进入时显示加载效果
  showPageLoading(pageName, options = {}) {
    const {
      skeletonType = 'default',
      loadingText = '页面加载中...',
      loadingTime = this.defaultLoadingTime,
      customClass = ''
    } = options

    // 记录页面加载状态
    this.pageLoadingStates.set(pageName, {
      startTime: Date.now(),
      loadingTime,
      skeletonType,
      loadingText,
      customClass,
      isDataLoaded: false
    })

    // 显示全局加载
    app.showGlobalLoading({
      skeletonType,
      loadingText,
      customClass
    })

    console.log(`页面加载开始: ${pageName}`)
  }

  // 页面数据加载完成
  onPageDataLoaded(pageName) {
    const loadingState = this.pageLoadingStates.get(pageName)
    if (!loadingState) return

    loadingState.isDataLoaded = true
    this.pageLoadingStates.set(pageName, loadingState)

    // 如果已经过了最小加载时间，立即隐藏
    const elapsedTime = Date.now() - loadingState.startTime
    if (elapsedTime >= this.minLoadingTime) {
      this.hidePageLoading(pageName)
    } else {
      // 否则等待最小加载时间
      const remainingTime = this.minLoadingTime - elapsedTime
      setTimeout(() => {
        this.hidePageLoading(pageName)
      }, remainingTime)
    }

    console.log(`页面数据加载完成: ${pageName}`)
  }

  // 隐藏页面加载
  hidePageLoading(pageName) {
    const loadingState = this.pageLoadingStates.get(pageName)
    if (!loadingState) return

    app.hideGlobalLoading()
    this.pageLoadingStates.delete(pageName)
    console.log(`页面加载隐藏: ${pageName}`)
  }

  // 强制隐藏页面加载（用于数据请求完成时）
  forceHidePageLoading(pageName) {
    const loadingState = this.pageLoadingStates.get(pageName)
    if (loadingState) {
      app.hideGlobalLoading()
      this.pageLoadingStates.delete(pageName)
      console.log(`强制隐藏页面加载: ${pageName}`)
    }
  }

  // 包装异步数据请求，自动管理加载状态
  async wrapDataRequest(pageName, requestFn, options = {}) {
    const {
      loadingText = '数据加载中...',
      errorText = '加载失败',
      showError = true
    } = options

    try {
      // 如果页面还没有开始加载，先显示加载状态
      if (!this.pageLoadingStates.has(pageName)) {
        this.showPageLoading(pageName, { loadingText })
      }

      const result = await requestFn()
      
      // 数据加载完成
      this.onPageDataLoaded(pageName)
      
      return result
    } catch (error) {
      console.error(`页面 ${pageName} 数据请求失败:`, error)
      
      // 隐藏加载状态
      this.forceHidePageLoading(pageName)
      
      if (showError) {
        wx.showToast({
          title: errorText,
          icon: 'none'
        })
      }
      
      throw error
    }
  }

  // 包装页面onLoad方法
  wrapPageOnLoad(originalOnLoad, pageName, options = {}) {
    return function(options) {
      // 显示页面加载效果
      const smartLoadingManager = require('./smartLoadingManager')
      smartLoadingManager.showPageLoading(pageName, options)
      
      // 执行原始onLoad方法
      if (originalOnLoad) {
        originalOnLoad.call(this, options)
      }
    }
  }

  // 包装页面onReady方法
  wrapPageOnReady(originalOnReady, pageName) {
    return function() {
      // 执行原始onReady方法
      if (originalOnReady) {
        originalOnReady.call(this)
      }
      
      // 页面准备完成，如果数据还没加载完成，等待数据加载
      const smartLoadingManager = require('./smartLoadingManager')
      const loadingState = smartLoadingManager.pageLoadingStates.get(pageName)
      
      if (loadingState && !loadingState.isDataLoaded) {
        // 数据还没加载完成，等待数据加载完成
        console.log(`页面 ${pageName} 准备完成，等待数据加载...`)
      } else {
        // 数据已经加载完成，隐藏加载状态
        smartLoadingManager.onPageDataLoaded(pageName)
      }
    }
  }

  // 根据页面类型获取合适的骨架屏类型
  getSkeletonTypeByPage(pageName) {
    const skeletonTypeMap = {
      'pages/service/index/index': 'service',
      'pages/user/mine/index': 'list',
      'pages/village/cases/index': 'card',
      'pages/village/complaints/index': 'card',
      'pages/user/progress/index': 'list',
      'pages/user/favorites/index': 'list',
      'pages/user/activities/index': 'card',
      'pages/common/index/index': 'default',
      'pages/village/open/index': 'default',
      'pages/village/notice-detail/index': 'default'
    }

    return skeletonTypeMap[pageName] || 'default'
  }

  // 根据页面类型获取合适的加载文本
  getLoadingTextByPage(pageName) {
    const loadingTextMap = {
      'pages/service/index/index': '服务事项加载中...',
      'pages/user/mine/index': '个人信息加载中...',
      'pages/village/cases/index': '案例信息加载中...',
      'pages/village/complaints/index': '投诉信息加载中...',
      'pages/user/progress/index': '进度查询加载中...',
      'pages/user/favorites/index': '收藏列表加载中...',
      'pages/user/activities/index': '活动信息加载中...',
      'pages/common/index/index': '首页加载中...',
      'pages/village/open/index': '村务公开加载中...',
      'pages/village/notice-detail/index': '村务信息加载中...'
    }

    return loadingTextMap[pageName] || '页面加载中...'
  }

  // 页面进入时的自动加载效果
  onPageEnter(pageName, options = {}) {
    const skeletonType = options.skeletonType || this.getSkeletonTypeByPage(pageName)
    const loadingText = options.loadingText || this.getLoadingTextByPage(pageName)
    const loadingTime = options.loadingTime || this.defaultLoadingTime

    this.showPageLoading(pageName, {
      skeletonType,
      loadingText,
      loadingTime,
      customClass: options.customClass
    })
  }
}

// 创建全局实例
const smartLoadingManager = new SmartLoadingManager()

// 导出工具函数
export const showPageLoading = (pageName, options) => smartLoadingManager.showPageLoading(pageName, options)
export const hidePageLoading = (pageName) => smartLoadingManager.hidePageLoading(pageName)
export const onPageEnter = (pageName, options) => smartLoadingManager.onPageEnter(pageName, options)
export const onPageDataLoaded = (pageName) => smartLoadingManager.onPageDataLoaded(pageName)
export const forceHidePageLoading = (pageName) => smartLoadingManager.forceHidePageLoading(pageName)
export const wrapDataRequest = (pageName, requestFn, options) => smartLoadingManager.wrapDataRequest(pageName, requestFn, options)
export const wrapPageOnLoad = (originalOnLoad, pageName, options) => smartLoadingManager.wrapPageOnLoad(originalOnLoad, pageName, options)
export const wrapPageOnReady = (originalOnReady, pageName) => smartLoadingManager.wrapPageOnReady(originalOnReady, pageName)

// 导出管理器实例
export default smartLoadingManager
